package itsen.com.bduidemo.modle.event.velocity;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.support.annotation.BoolRes;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;

import itsen.com.bduidemo.lib.tool.LogTool;

/**
 * Created by 周德森
 * Created time 2017/10/20 16:50
 * Description:DNui
 * Version: V 1.0
 */

public class VelocityView extends View{
    private Paint paint;
    private String textColor = "";
    private VelocityTracker velocityTracker;
    private float speedX = 0;
    private float speedY = 0;
    public VelocityView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init(){
        paint = new Paint();
        paint.setTextSize(50);
        paint.setStyle(Paint.Style.FILL);
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                if (velocityTracker == null){
                    velocityTracker = VelocityTracker.obtain();
                }else {
                    velocityTracker.clear();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                velocityTracker.addMovement(event);
                //设置单位，1000 表示每秒多少像素（pix/second),1代表每微秒多少像素（pix/millisecond)。
                velocityTracker.computeCurrentVelocity(1000);
                speedX = velocityTracker.getXVelocity();
                speedY = velocityTracker.getYVelocity();
                LogTool.e("speedx:"+velocityTracker.getXVelocity());
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                speedX = velocityTracker.getXVelocity();
                speedY = velocityTracker.getYVelocity();
                invalidate();
                break;
            case MotionEvent.ACTION_CANCEL:
                velocityTracker.recycle();
                break;
        }
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText("speedx:"+speedX+"  speedy:"+speedY,100,100,paint);
    }
}
